define(function(require, exports){
	var $ = require("jquery");
	var pubjs = require('pubjs');
	var view  = require('@base/view');
	var util = require('util');
	var dspUtil = require('dspUtil');
	var common = require('modules/common');
	
	var OutLink = view.container.extend({
		init: function(config){
			config = pubjs.conf(config, {
				'tplFile':	'/tpl/sweety/tab/outLink.tpl'
				,'urlGetMaterial': 'sweety/getMaterial'
				,'view_model': {
					'vmRemove': this.vmRemove,
					'vmImport': this.vmImport,
					'urls': '',
					'vmPreview': this.vmPreview,
					'images': [],
					'skip': []
				}
			});

			this.$guid = 0;
			this.$size = {};
			this.Super('init', arguments);
		},
		afterBuild: function(){
			this.buildFromTemplate({});
		},
		vmPreview: function (thumb) {
			window.open(thumb);
		},
		vmImport: function () {
			var vm = this.vm.$;
			if(!vm.urls)
			{
				pubjs.alert(LANG('请填入地址'));
				return false;
			}

			var urls = dspUtil.url_get(vm.urls);
			if(!urls.length)
			{
				pubjs.alert(LANG('请确认地址的合法性，以回车来换行。一行一个地址'));
				return false;
			}

			var c = this.getConfig();
			var self = this;
			pubjs.loading.show();
			pubjs.mc.send(c.urlGetMaterial, {Urls: urls}, function (err, data) {
				pubjs.loading.hide();
				if(err)
				{
					return pubjs.alert(err.message);
				}

				if(data && data.valid && data.valid.length)
				{
					self.appendMaterial(data.valid);
				}

				if(data && data.error && data.error.length)
				{
					pubjs.alert(LANG('拉取数据错误或大小不正确的地址：%1', data.error.join('\n')));
				}
			});
		},
		appendMaterial: function (data) {
			var vm = this.vm.$;
			var images = vm.images;
			var self = this;
			if(!Array.isArray(data))
			{
				data = [data];
			}

			util.each(data, function (item) {
				item._guid = self._guid();
				self._formatMedia(item);
				if(!self.$size[item.f_size])
				{
					self.$size[item.f_size] = [];
				}

				self.$size[item.f_size].push(item._guid);
				images.push(item);
			});

			vm.urls = '';
			self._checkSize();
			return false;
		},
		_checkSize: function () {
			var vm = this.vm.$;
			var conflict = [];
			for(var size in this.$size)
			{
				if(this.$size.hasOwnProperty(size) && this.$size[size].length > 1)
				{
					Array.prototype.push.apply(conflict, this.$size[size]);
				}
			}

			for(var i = 0; i < vm.images.length; i++)
			{
				vm.images[i].conflict = conflict.indexOf(vm.images[i]._guid) > -1;
			}
		},
		_formatMedia: function (data) {
			if(data)
			{
				data.smallThumb = data.thumb + '&w=100&h=100';
				data.shape = `${data.width} * ${data.height}`;
				data.f_size = dspUtil.sizeFormat((data.size/1024), 2);
				data.conflict = false;
				if(!data.name)
				{
					data.name = LANG('新建外链_') + util.date('YmdHis');
				}
			}

		},
		vmRemove: function (index) {
			var vm = this.vm.$;
			var item = vm.images.splice(index, 1)[0];
			if(this.$size[item.f_size])
			{
				var i = this.$size[item.f_size].indexOf(item._guid);
				this.$size[item.f_size].splice(i, 1);
			}
			this._checkSize();
		},
		reset: function () {
			this.vm.reset();
			this.$guid = 0;
			this.$size = {};
			return this;
		},
		_guid: function () {
			return ++this.$guid;
		},
		getData: function () {
			var data = [];
			var vm = this.vm.$;
			var skip = !!vm.skip.length;
			for(var i = 0; i < vm.images.length; i++)
			{
				var image = vm.images[i];
				var item;
				if(image.creativeId)
				{
					item = {
						CreativeId: image.creativeId || 0
					};
				}
				else
				{
					item = {
						Size: image.size
						,Height: image.height
						,Width: image.width
						,Url: image.url
						,FileType: image.type
						,Duration: image.duration || 0
						,Path: image.path
						,IsVideo: image.isVideo
					}
				}

				item.Skip = skip;
				item.Name = image.name;
				item.type = 'outLink';
				data.push(item);
			}

			return data;
		},
		setData: function (data) {
			var vm = this.vm.$;
			var items = [];
			var skip;
			if(data && data.length)
			{
				for(var item of data)
				{
					items.push({
						size: item.Material.FileSize,
						width: item.Width,
						height: item.Height,
						type: item.Material.FileType,
						isVideo: !!item.Video.Duration,
						duration: item.Video.Duration,
						name: item.Name,
						thumb: item.Thumb,
						url: item.Link,
						creativeId: item._id || 0
					});

					if(!skip)
					{
						skip = item.AllowSkip ? ['1'] : [];
					}
				}
			}

			vm.skip = skip;
			this.appendMaterial(items);
		},
		validate: function () {
			for(var size in this.$size)
			{
				if(this.$size.hasOwnProperty(size) && this.$size[size].length > 1)
				{
					pubjs.alert(LANG('尺寸重复'));
					return false;
				}
			}

			return true;
		}
	});
	
	exports.outLink = OutLink;

	// 本地上传 - 尺寸重复弹出窗口
	var RepeatPopWin = view.widget.extend({
		init: function(config) {
			config = pubjs.conf(config, {
				'layout': {
					'class': 'P-sweetyRepeatPop',
					'module': '@base/dialog.base',
					'title': LANG("素材尺寸重复"),
					'size': null,
					'width': 600,
					'showClose': false,
					'buttons': [null, 'ok'],
					'silence': false
				}
			});

			this.Super('init', arguments);
		},
		afterBuild: function() {
			var container = this.getContainer();
			container.append([
				'<p>' + LANG("请选择需要投放的素材，每个尺寸只能选择一个") + '</p>',
				'<div class="P-sweetyRepeatPopContainer" pub-name="scroller" pub-mod="@base/common/base.scroller">',
				'<div class="P-sweetyRepeatPopMain"></div>',
				'</div>'
			].join(''));

			this.$container = container.find('.P-sweetyRepeatPopMain');

			this.buildFromTemplate({
				'scroller': {
					'dir': 'V',
					'offset': 0
				}
			});
		},
		afterBuildTemplate: function(){
			if(util.isMobile()){
				this.getDOM().find('.P-sweetyRepeatPopContainer').css('overflow-y', 'auto');
			}
		},
		reset: function() {
			this.$container.empty();
			return this;
		},
		show: function() {
			this.Super('show', arguments);
			this.$.scroller.update();
			return this;
		},
		setData: function(repeatItems) {
			var self = this;
			var container = self.$container;
			var defaultImage = window.ROOT('resources/images/default.png');
			self.$data = repeatItems;
			util.each(repeatItems, function(item) {
				var el = $('<div class="P-sweetyRepeatPopItem"></div>').appendTo(container);
				$('<div class="P-sweetyRepeatPopItemHead"></div>').appendTo(el).text([item.width, item.height].join('*'));
				var body = $('<ul class="P-sweetyRepeatPopItemBody"></ul>').appendTo(el);

				item.selected = null;
				util.each(item.files, function(file) {
					var isTemp = !!file.data;
					var data = isTemp ? file.data : file;
					var id = isTemp ? ('fid_' + data.fileId) : data.id;
					var previewUrl = data.previewUrl;

					var subEl = $([
						'<li class="P-sweetyRepeatPopItemSub">',
							'<div class="itemSubPic">',
								'<img alt="' + LANG('缩略图') + '" src="' + defaultImage + '"/>',
							'</div>',
							'<div class="itemSubInfo">',
								'<div class="itemSubName">' + (data.name || '') + (isTemp ? '<i class="itemSubNew">*</i>' : '') + '</div>',
								'<span class="itemSubType">',
									LANG("类型：") + '<em>' + (data.type || '') + '</em>',
								'</span>',
								'<span class="itemSubFileSize">',
									LANG("大小：") + '<em>' + (data.size || '') + '</em>',
								'</span>',
								'<div class="itemSubSize">',
									LANG("尺寸：") + '<em>' + ([data.width, data.height].join('*')) + '</em>',
								'</div>',
							'</div>',
							'<div class="itemSubCtrl">',
								'<a href="#" class="itemSubSelect">' + LANG('选择') + '</a>',
								'<a href="' + previewUrl + '" class="itemSubPreview" target="_blank">' + LANG('预览') + '</a>',
							'</div>',
						'</li>'
					].join('')).appendTo(body);

					if(data.thumb) {
						var thumb = data.thumb + '&w=65&h=65';
						common.loadImage('creative', thumb, subEl.find('.itemSubPic img'));
					}

					self.uiBind(subEl.find('.itemSubSelect'), 'click', [item, file], 'eventFileSelectToggle');
				});

			});

			return self;
		},
		eventFileSelectToggle: function(evt) {
			var data = evt.data;
			data[0].selected = data[1].id;
			var subItem = $(evt.currentTarget).parents('.P-sweetyRepeatPopItemSub');
			subItem.siblings('li').removeClass('selected');
			subItem.addClass('selected');
			evt.preventDefault();
		},
		onDialogOk: function(ev) {
			var selected = [];
			var unused = [];
			var notPass = false;
			util.each(this.$data, function(item) {
				if (!item.selected) {
					notPass = true;
				} else {
					selected.push(item.selected);
					util.each(item.files, function(file) {
						if (file.id != item.selected) {
							unused.push(file.id);
						}
					});
				}
			});

			if (notPass) {
				pubjs.alert(LANG("还有未选择的尺寸"));
			} else {
				this.hide();
				this.fire('selectRepeatCreativeOk', [selected, unused]);
			}
			return false;
		}
	});

	// 选项卡-本地上传
	var Upload = view.container.extend({
		init: function(config){
			config = pubjs.conf(config, {

			});

			this.$creatives = []; // 创意数据集合

			this.Super('init', arguments);
		},
		afterBuild: function(){

			this.append([
				'<div pub-name="uploader" pub-mod="modules/upload.base"></div>'
			].join(''));

			this.create('repeat', RepeatPopWin);

			var param = $.extend({}, pubjs.config('uploader/creative'), {
				'target': this.getDOM(),
				'class': 'pd15',
				'subModule': 'sweety/upload/uploader.base',
				'hasProgress': true
			});

			if(pubjs.checkRight('sweetyCreative.html'))
			{
				param.filters.mime_types.push(
					{ title : "html文件", extensions : "html" }
				);
			}

			var config = {
				'uploader': param
			}
			this.buildFromTemplate(config);
		},
		onUploadComplete: function(ev) {
			this.checkSizeRepeat(ev.param);
		},
		// 检查尺寸重复
		checkSizeRepeat: function(files) {
			var self = this;
			var sizeGroup = {};
			util.each(files, function(file) {
				var data = file.data;
				if (!data) {
					return false;
				}
				var width = data.width;
				var height = data.height;
				var key = [width, height].join('*');

				if (!sizeGroup[key]) {
					sizeGroup[key] = {
						width: width,
						height: height,
						files: []
					};
				}
				sizeGroup[key].files.push(file);
			});

			// 编辑状态下，检测重复尺寸，如果新添加的有重复，点击确定删除新添加的
			util.each(self.$creatives, function(creative){
				if(creative){
					var key = [creative.width, creative.height].join('*');
					if(!sizeGroup[key])
					{
						sizeGroup[key] = {
							width: creative.width,
							height: creative.height,
							files: []
						}
					}
					sizeGroup[key].files.push(creative);
				}
			});

			var repeatItems = [];
			util.each(sizeGroup, function(item) {
				if (item.files.length > 1) {
					repeatItems.push(item);
				}
			});

			if (repeatItems.length) {
				this.$.repeat.reset().setData(repeatItems).show();
				return true;
			}
			return false;
		},
		// 选择重复尺寸完成
		onSelectRepeatCreativeOk: function(ev) {
			var unused = ev.param[1];
			var self = this;
			util.each(unused, function(id) {
				self.$.uploader.removeItem(id);
				util.remove(self.$creatives, id, 'id');
			});
			return false;
		},
		// 删除广播接收
		onUploaderItemDeleted: function(ev){
			var self = this;
			// 移除时，同时删除已记录在creatives里的数据
			if(ev.param.id){
				util.remove(self.$creatives, ev.param.id, 'id');
			}
			return false;
		},
		getData: function(){
			return this.$.uploader.getValue();
		},
		reset: function(){
			this.$creatives = [];
			this.$.uploader.reset().clearFiles();
		},
		setData: function(data){
			var details = [];
			data.forEach(function(creative){
				var detail = {};
				detail.id = creative._id;
				detail.name = creative.Name;
				detail.type = creative.Material.FileType;
				detail.size = creative.Material.FileSize && ((Number(creative.Material.FileSize / 1024)).toFixed(1) + "KB");
				detail.width = creative.Width;
				detail.height = creative.Height;
				detail.thumb = creative.Thumb;
				detail.path = creative.Path;
				detail.previewUrl = creative.PreviewUrl;
				details.push(detail);
			});

			// 记录一下创意数据
			this.$creatives = util.clone(details);

			this.$.uploader.setValue(details);
		}
	});
	exports.upload = Upload;

	// 选项卡-自定义物料
	var Custom = view.container.extend({
		init: function(config){
			config = pubjs.conf(config, {
				'class': 'uk-form',
				'tplFile':	'/tpl/sweety/tab/uploadCustom.html',
				'view_model': {
					'data' : []
					,'checkUri': this.vmCheckUri
					,'closeItem': this.vmCloseItem
					,'vmSSLSelect': this.vmSSLSelect
					,'valid': []
				}
			});

			this.Super('init', arguments);
		},
		afterBuild: function(){
			this.buildFromTemplate({
				'add': {
					'value': LANG('添加'),
					'class': 'btn btn-default mt10'
				}
			});
		},
		afterBuildTemplate: function(){
			this.addItem();
		},
		vmSSLSelect: function(i){
			var data = this.vm.$.data[i];
			if(data.isSSL && ~data.admUri.indexOf('http://'))
			{
				pubjs.alert('如选择了SSL，请确保地址里不能包含http://');
				return false;
			}
		},
		vmCloseItem: function(i){
			this.vm.$.data.splice(i,1);
			this.vm.$.valid.splice(i,1);
		},
		vmCheckUri: function(i){
			var vm = this.vm.$;
			var uri = vm.data[i].admUri;
			var name = vm.data[i].Name;
			if(uri === ''){
				return;
			}
			//dco的创意暂时跳过检查吧。
			if (uri.match(/^\d+\.\d+$/g)) {
				return ;
			}
			pubjs.mc.send('creative/uploadAdm', {url: uri}, function(err, data){
				if(err){
					pubjs.alert(err.message);
					vm.valid[i] = false;
					return false;
				}
				var tmpData = {
					_id		: data.data._id || 0,
					Width	: data.data.Width,
					Height	: data.data.Height,
					Type	: data.data.Type,
					Thumb	: data.data.Thumb,
					isSSL   : vm.data[i].isSSL,
					Name	: name || data.data.Name,
					admUri	: uri,
					AdmUrl	: (pubjs.config('materialPreview/admCreative') || '').replace(/\{url\}/, uri)
				};
				vm.data.splice(i, 1, tmpData);
				vm.valid.splice(i, 1, true);
			})
		},
		onInputClick: function(ev){
			if(ev.name == 'add'){
				this.addItem();
			}
		},
		addItem: function(){
			this.vm.$.data.push({
				'admUri': ''
				,'isSSL': false
				,'AdmUrl': ''
				,'Width': ''
				,'Height': ''
				,'Type': ''
				,'Thumb': ''
				,'Name': ''
				,'_id': ''
			});
			this.vm.$.valid.push(false);
		},
		getData: function(){
			var data = this.vm.getItem('data');
			var result = [];
			util.each(data, function(value, index){
				result[index] = {
					'url'			: value.admUri,
					'isSSL'         : value.isSSL,
					'type'			: 'custom',
					'creativeId'	: value._id || 0,
					'name'			: value.Name
				};
			});
			return result;
		},
		validate: function(data)
		{
			var state = true;
			util.each(data, function(item) {
				if(item.isSSL && ~item.url.indexOf('http://'))
				{
					state = false;
					pubjs.alert(LANG('地址包含http://，请删除http://，再进行保存。'));
					return false;
				}
			});

			return state;
		},
		reset: function(){
			this.vm.reset();
			this.addItem();
			this.vm.$.valid = [false];
			return this;
		},
		setData: function(data){
			var self = this;
			var vm = self.vm.$;
			util.each(data, function(value, index){
				if(index !== 0){
					self.addItem();
				}
				var isSSL = false;
				if(value.Adm && value.Adm.SSL)
				{
					isSSL = true;
				}
				var tmpData = {
					_id		: +value._id || 0,
					Width	: value.Width,
					Height	: value.Height,
					Type	: value.Material.FileType,
					Thumb	: value.Thumb,
					Name	: value.Name,
					isSSL   : isSSL,
					//输入框的url
					admUri  : value.Adm.Url,
					//预览的地址
					AdmUrl  : (pubjs.config('materialPreview/admCreative') || '').replace(/\{url\}/, value.Adm.Url)
				};
				vm.data.splice(index, 1, tmpData);
				vm.valid.splice(index, 1, true);
			});
		}
	});
	exports.custom = Custom;

	// 选项卡-图文创意
	var PTC_CONF = pubjs.config('CONST/PTC');
	var FIELD_TYPE = PTC_CONF.FIELD_TYPE;
	var adx_map = pubjs.config('channelMap');
	
	var PicText = view.container.extend({
		init: function(config){
			config = pubjs.conf(config, {
				'tplFile':	'/tpl/sweety/tab/picText.html'
				,'urlChannel': 'ptc/adx'
				,'urlTemplate': 'ptc/list'
				,'view_model': {
					"template": []
					,'vmClose': this.vmClose
					,'vmRemoveTemplate': this.vmRemoveTemplate
					,'vmContentChange': this.vmContentChange
					,'TYPE_MAP': FIELD_TYPE
					,'vmRadioChange': this.vmRadioChange
				}
				,'uploader': {
					url : '/api/dsp/upload?type=sweetyCreative',
					hasTip: false,
					title: '上传主素材',
					filters: {
						mime_types : [ //只允许上传图片文件和rar压缩文件
							{ title : "图片文件", extensions : "jpg,jpeg,gif,png" }
						],
						multi_selection: false										// 单选上传
						//max_file_size : '10000kb'								// 最大只能上传100kb的文件
						// prevent_duplicates : true								// 不允许队列中存在重复文件
					}
				}
				,ptcUrl: '/api/dsp/upload?type=sweetyCreative'
			});
			
			this.$templateIds = [];
			this.$guid = 1;
			this.Super('init', arguments);
		},
		afterBuild: function(){
			this.buildFromTemplate({
				select: {
					'value': LANG('选择模块')
					,'class': 'btn btn-success'
					,'width': null
				}
			});
		},
		vmRadioChange: function (template) {
			this.checkView(template);
		},
		vmContentChange: function(field) {
			switch (field.byte) {
				case 1:
					field._len = field.content.length;
					break;
				default :
					field._len = dspUtil.byteLen(field.content);
					break;
			}
		},
		vmRemoveTemplate: function(parent, index) {
			var self = this;
			var template = self.vm.$.template;
			if(template && template.length)
			{
				var tmp = template[index];
				var tmpId = [tmp.AdxId, tmp.templateId].join('_');
				if(self.$conflict && self.$conflict[tmpId]) {
					util.each(self.$conflict[tmpId], function(id) {
						template[id].conflict = false;
					});
					
					delete self.$conflict[tmpId];
				}
				
				template.splice(index, 1);
			}
		},
		getData: function(){
			var self = this;
			var template = self.vm.getItem('template');
			// 不知道为什么这里的mvvm 取出的view 竟然是空的，直接拿出来就有值。神了我的哥。
			var view_tem = self.vm.$.template;
			var data = [];
			var keyMap = {};
			util.each(template, function(template, j) {
				var view = view_tem[j].view;
				var tmpId = [template.AdxId, template.templateId].join('_');
				template.type = 'picText';
				util.each(template.fields, function(t) {
					self.getField(t);
					if(view[t.field] === false)
					{
						return null;
					}
				});
				
				data.push(template);
				if(!keyMap[tmpId]) {
					keyMap[tmpId] = [];
				}
				
				keyMap[tmpId].push(j);
				self.$conflict = keyMap;
			});
			
			return data;
		},
		getField: function(t) {
			var self = this;
			if(t.type == FIELD_TYPE.IMAGE || t.type == FIELD_TYPE.VIDEO) {
				t.upload = self.$['SubUpload_' + t.guid].getValue();
				if(t.multi)
				{
					t.upload = t.upload || [];
				}
				else
				{
					t.upload = t.upload && t.upload[0] || null;
				}
			}
			if(t.isCss) {
				t.content = t.content.replace(/(\n)+|(\r\n)+|(；)/g, ';');
			}
			
			return t;
		},
		validate: function(data) {
			if(!data || !data.length) {
				pubjs.alert(LANG('图文创意不能为空.'));
				return false;
			}
			
			var self = this;
			var template = this.vm.$.template;
			var keyMap = this.$conflict;
			var valid = true;
			if(keyMap) {
				util.each(keyMap, function(item){
					if(item && item.length > 1){
						valid = false;
						util.each(item, function(sub) {
							template[sub].conflict = true;
						});
					}
				});
			}
			
			if(!valid){
				pubjs.alert(LANG('相同渠道下相同的模板不能保存多个'));
				return false;
			}
			
			valid = true;
			var name = [];
			util.each(data, function(template) {
				if(!template.name) {
					pubjs.alert(LANG('请输入创意的名称'));
					valid = false;
					return false;
				}
				
				if(name.indexOf(template.name) > -1)
				{
					pubjs.alert(LANG('模板名称冲突了.'));
					valid = false;
					return false;
				}
				else
				{
					name.push(template.name);
				}
				
				util.each(template.fields, function(item) {
					if(item.type == FIELD_TYPE.TEXT)
					{
						if(!self.maxCompare(item))
						{
							pubjs.alert(LANG('模板里的值长度不能大于 ' + item.max));
							valid = false;
							return false;
						}
						
						if(!self.minCompare(item))
						{
							pubjs.alert(LANG('模板里的内容模板里的值长度不能少于 ' + item.min || 0));
							valid = false;
							return false;
						}
						
						if(item.checkForm && util.isString(item.checkForm)){
							var funs = item.checkForm.split(',');
							var check = true;
							util.each(funs, function(fun){
								if(fun && CHECKFORM[fun]){
									check = CHECKFORM[fun](item.content, item);
									if(!check) {
										return false;
									}
								}
							});
							
							if(!check){
								valid = false;
								return false;
							}
						}
					}
					else if(item.type == FIELD_TYPE.IMAGE || item.type == FIELD_TYPE.VIDEO)
					{
						//	if((!item.notRequired && (!item.upload || !item.upload.length)))
						if(!item.notRequired)
						{
							if((util.isArray(item.upload) && item.upload.length == 0) ||
								(!util.isArray(item.upload) && !item.upload))
							{
								pubjs.alert(LANG('%1 素材不能为空 请上传', item.title));
								valid = false;
								return false;
							}
						}
						/*						if((!item.notRequired && !item.upload))
						 {
						 pubjs.alert(LANG('%1 素材不能为空 请上传', item.title));
						 valid = false;
						 return false;
						 }*/
						
						var uploads = item.upload;
						if(!util.isArray(uploads))
						{
							uploads = [uploads];
						}
						
						util.each(uploads, function(upload) {
							if(upload)
							{
								if(item.width && item.width != upload.width)
								{
									pubjs.alert(LANG('%1 尺寸不正确', item.title));
									valid = false;
									return false;
								}
								
								if(item.height && item.height != upload.height)
								{
									pubjs.alert(LANG('%1 尺寸不正确', item.title));
									valid = false;
									return false;
								}
								
								if(item.duration && item.duration != upload.duration)
								{
									pubjs.alert(LANG('%1 时长不正确', item.title));
									valid = false;
									return false;
								}
							}
						});
						
						if(!valid)
						{
							return false;
						}
					}
					else if(item.type == FIELD_TYPE.RADIO && !item.content)
					{
						pubjs.alert(LANG('Radio 的选项不要不填'));
						valid = false;
						return false;
					}
				});
				
				if(!valid) {
					return false;
				}
			});
			
			return valid;
		},
		maxCompare: function(item) {
			return !(item.hasOwnProperty('max') && item._len > item.max);
		},
		minCompare: function(item) {
			return !(item.hasOwnProperty('min') && item._len < item.min);
		},
		reset: function(){
			var self = this;
			var ch = self.$;
			for(var name in ch)
			{
				if(ch.hasOwnProperty(name) && (name.indexOf('SubUpload_') > -1))
				{
					ch[name].destroy();
				}
			}
			
			self.vm.reset();
			return this;
		},
		setData: function(data){
			var self = this;
			var templates = [];
			if(data && data.length) {
				util.each(data, function(template) {
					//template.name = template.Name;
					template.conflict = false;
					util.each(template.fields, function(da) {
						self.formatField(da);
					});
					
					self.checkView(template);
					templates.push(template);
				});
			}
			
			self.vm.$.template = templates;
			self.createAsyncModule();
		},
		onInputClick: function(ev) {
			var self = this;
			var c = this.getConfig();
			switch (ev.name) {
				case 'select':
					this.showSelect();
					break;
				default :
					return false;
			}
			
			return false;
		},
		showSelect: function()
		{
			var self = this;
			var mod = self.$.selectPop;
			if(!mod)
			{
				this.createAsync('selectPop',"sweety/popwin/picText.selectTemplate", {
				},function(mod) {
					mod.reset().show();
				})
			}
			else
			{
				mod.reset().show();
			}
		},
		onTemplateSelect: function(ev)
		{
			var self = this;
			var templateIds = this.$templateIds;
			var c = this.getConfig();
			if(ev && ev.name === 'selectPop')
			{
				var newIds = ev.param && ev.param.value;
				//todo 先不检查相同的。
				if(newIds && newIds.length)
				{
					pubjs.loading.show();
					pubjs.mc.send(c.urlTemplate, {
						ids: newIds, needAdx: true, needField: true
					}, function(err, data) {
						pubjs.loading.hide();
						if(err)
						{
							return pubjs.alert(err.message);
						}
						
						if(data && data.items)
						{
							util.each(data.items, function(item) {
								delete item._id;
								self.addTemplate(item);
							});
							
							self.createAsyncModule();
						}
					});
					
				}
			}
			
		},
		addTemplate: function(item)
		{
			var self = this;
			if(item)
			{
				item.name = '';
				item.conflict = false;
				if(item.fields && item.fields.length)
				{
					util.each(item.fields, function(f) {
						self.formatField(f);
					});
				}
			}
			
			self.checkView(item);
			this.vm.$.template.push(item);
		},
		checkView(template)
		{
			var df = '';
			template.view = {};
			util.each(template.fields, function(f) {
				template.view[f.field] = true;
				df += `var ${f.field} = '${f.content}';`;
			});
			
			util.each(template.fields, function(f) {
				if(f.condition)
				{
					template.view[f.field] = (new Function(`${df}; return ${f.condition}`))();
				}
			});
		},
		createAsyncModule: function() {
			var self = this;
			var upload_field = [];//模板下的图片视频上传 字段集合
			var template = self.vm.$.template;
			util.each(template, function(item) {
				util.each(item.fields, function(d) {
					if(d.type == FIELD_TYPE.IMAGE || d.type == FIELD_TYPE.VIDEO) {
						upload_field.push(d);
					}
				});
			});
			
			var name = '';
			var ch = self.$;
			var param = self.getConfig('uploader');
			
			if(upload_field.length){
				util.each(upload_field, function(item){
					if(item){
						var tmp = item;
						name = 'SubUpload_'+ tmp.guid;
						var uploadData = null;
						if(ch && ch[name]) {
							uploadData = ch[name].getValue();
							ch[name].destroy();
						}
						
						if((!uploadData || !uploadData.length) && tmp.upload) {
							uploadData = tmp.upload;
						}
						
						var uploadFilter = {
							'target': self.$el.find('#upload_' + tmp.guid)
							,'title': LANG('上传图片')
							,'multi_selection': item.multi
							,'subModule': 'sweety/upload/uploader.picText'
							,'url': self.getConfig('ptcUrl')
							,'class': 'P-sweetyPicTextUploadBox'
							,'filters': {}
						};
						
						uploadFilter.sub_conf = uploadFilter.sub_conf || {};
						if(tmp.height && tmp.width)
						{
							uploadFilter.sub_conf = {
								width: tmp.width
								,height: tmp.height
								,duration: tmp.duration
							};
						}
						
						if(tmp.duration)
						{
							uploadFilter.sub_conf.duration = tmp.duration;
						}
						
						if(tmp.type == FIELD_TYPE.VIDEO)
						{
							uploadFilter.title = LANG('上传视频');
							uploadFilter.filters = {
								mime_types : [
									{ title : "视频文件", extensions : item.extensions || pubjs.config('video_type') }
								]
							};
							
							uploadFilter.sub_conf.assist_conf = {
								type: 'picTextVideo'
							}
						}
						else
						{
							uploadFilter.filters.mime_types = [
								{ title : "图片文件", extensions : item.extensions || 'jpg,jpeg,gif,png' }
							];
						}
						
						uploadFilter.filters.max_file_size = '20mb';
						if(tmp.limit)
						{
							uploadFilter.filters.max_file_size = (tmp.limit || '300') + 'kb';
						}
						
						
						if(uploadFilter.target)
						{
							self.createAsync(name, 'modules/upload.base', $.extend({}, param, uploadFilter), function(mod) {
								if(uploadData)
								{
									mod.setValue(uploadData);
								}
							});
						}
					}
				})
			}
		},
		guid: function() {
			return this.$guid++;
		},
		formatField: function(da) {
			var self = this;
			da.content = da.content || da.defaultValue || '';
			da.description = da.description || '';
			da.guid = self.guid();
			switch (da.type)
			{
				case FIELD_TYPE.TEXT:
					da.max = da.max || 99;
					da.min = da.min || 0;
					self.vmContentChange(da);
					break;
				case FIELD_TYPE.RADIO:
					da.content = da.content || (da.options && da.options[0] && da.options[0].value) || '';
					break;
				case FIELD_TYPE.IMAGE:
				case FIELD_TYPE.VIDEO:
					da.terms = `
						${LANG('尺寸')}: ${da.width ? da.width : LANG('不限')} ${da.height ? (' x ' + da.height) : ''};
						${LANG('类型')}: ${da.extensions || LANG('不限')};
					`;
					if(da.limit)
					{
						da.terms += `${LANG('小于')}: ${dspUtil.sizeFormat(da.limit)}};`;
					}
					else
					{
						da.terms += LANG('大小: 不限;');
					}
					
					if(FIELD_TYPE.VIDEO == da.type && da.duration)
					{
						da.terms += `${LANG('时长')}: ${da.duration} ${LANG('秒')};`
					}
					if(da.description)
					{
						da.terms += `${da.description};`
					}
					if(da.multi)
					{
						da.terms += LANG('支持多张图片');
					}
					
					
					break;
			}
			
			if(da.isCss) {
				da.content = da.content.replace(/;/g,';\n');
			}
			
			return da;
		}
	});
	exports.picText = PicText;
	var CHECKFORM = {
		// 中文标点符号结尾要求
		punctuation: function(text, field) {
			var result = true;
			if(text){
				result = /[。！？……]$/.test(text);
			}
			if(!result){
				pubjs.alert(LANG('"%1"必须以标点符号结尾，仅支持支持句号、感叹号、问号、省略号结尾。', field.title));
			}

			return result;
		}
	};

	// 选项卡-视频外链
	var VideoOuterlink = view.container.extend({
		init: function(config) {
			config = pubjs.conf(config, {
				'class': 'uk-form',
				'tplFile': '/tpl/sweety/tab/videoOuterlink.html',

				'videoTypes': [
					{id: 'mp4', name: 'MP4'},
					{id: 'flv', name: 'FLV'},
					{id: 'webm', name: 'WEBM'}
				],

				'defaultItemCount': 1,      // 默认创意个数
				'defaultItemLinkCount': 3,  // 默认创意下视频链接输入框个数
				'itemLimit': 20,            // 创意个数限制
				'itemLinkLimit': 10,        // 视频链接个数限制

				'view_model': {
					// 创意数据
					'data': [],
					// 添加一个创意
					addItem: this.addItem,
					// 删除一个创意
					removeItem: this.removeItem,
					// 为某个创意添加一个视频链接
					addLinkItem: this.addLinkItem,
					// 删除某个创意的一个链接
					removeLinkItem: this.removeLinkItem,
					// 视频链接循环渲染回调
					afterLinkRepeatRendered: this.afterLinkRepeatRendered,
					// 视频链接变更事件
					eventUriChange: this.eventUriChange
				}
			});

			var c = config.get();
			c.view_model.itemLimit = c.itemLimit;
			c.view_model.itemLinkLimit = c.itemLinkLimit;

			this.Super('init', arguments);
		},
		afterBuild: function() {
			this.reset();
		},
		// 添加一个创意
		addItem: function() {
			var c = this.getConfig();

			var item = this.initItemFields(item);

			var i = 0;
			while(i++ < c.defaultItemLinkCount) {
				this.addLinkItem(item);
			}

			this.vm.$.data.push(item);
		},
		// 初始化创意的数据结构
		initItemFields: function(item) {
			return util.extend({
				creativeId: 0,
				// 名称
				name: LANG('新建创意包')+'_'+ util.date('YmdHis') + '_' + LANG('视频外链'),
				// 宽度
				width: '',
				// 高度
				height: '',
				// 是否允许跳过
				allowSkip: false,
				// 视频链接
				links: []
			}, item || {}, {type: 'videoLink'});
		},
		/**
		 * 删除一个创意
		 * @param  {Number} index 创意索引
		 */
		removeItem: function(index) {
			this.vm.$.data.splice(index, 1);
		},
		/**
		 * 为某个创意添加一个视频链接
		 * @param {Object} item 视频链接对象
		 */
		addLinkItem: function(item) {
			if (item) {
				if (!item.links) {
					item.links = [];
				}

				item.links.push(this.initLinkItemFields());
			}

			return item;
		},
		// 初始化视频链接的数据结构
		initLinkItemFields: function(linkItem) {
			return util.extend({
				// 视频类型模块名称
				_typeModuleName: util.guid('link_type_'),
				// 链接uri
				uri: '',
				// 视频类型
				type: '',
				// 视频长度
				time: '',
				// 加载状态
				_loading: false
			}, linkItem || {});
		},
		/**
		 * 删除某个创意的一个视频链接
		 * @param  {Number} index 视频链接索引
		 * @param  {Object} item  创意对象
		 */
		removeLinkItem: function(index, item) {
			if (item) {
				item.links.splice(index, 1);
			}
		},
		/**
		 * 视频链接循环渲染回调
		 * @param  {String} action 数据变更类型
		 */
		afterLinkRepeatRendered: function(action) {
			if (action === 'add') {
				var cfg = {};
				var types = this.getConfig('videoTypes');
				util.each(this.vm.getItem('data'), function(item) {
					util.each(item.links, function(link) {
						cfg[link._typeModuleName] = {
							width: 150,
							options: types,
							value: link.type || null,
							def: LANG("请选择视频类型"),
							panel_config: {
								hasSearch: false
							}
						}
					});
				});
				this.buildFromTemplate(cfg);
			}
		},
		/**
		 * 某个创意的视频链接变更事件
		 * @param  {String} uri   当前视频链接
		 * @param  {Object} link  视频链接对象
		 * @param  {Object} item  创意对象
		 */
		eventUriChange: function(uri, link, item) {
			if (uri) {
				this.loadLinkInfo(uri, link, item);
			}
		},
		// 获取视频链接附加信息
		loadLinkInfo: function(uri, link, item) {
			link._loading = true;
			pubjs.mc.send('sweety/videoInfo', {url: uri}, this.afterLoadLinkInfo.bind(this, link));
		},
		afterLoadLinkInfo: function(link, err, data) {
			link._loading = false;

			if (err) {
				return pubjs.alert(err.message);
			}

			var cs = this.$ || {};
			if (cs && cs[link._typeModuleName]) {
				cs[link._typeModuleName].setValue(data.Type);
			}
			link.time = parseInt(data.Duration, 10) + LANG("秒");
		},
		reset: function(noAdd) {
			var c = this.getConfig();
			var i = 0;

			// 先清空
			util.each(this.vm.getItem('data'), function(item, index) {
				this.removeItem(index);
			}, this);

			if (!noAdd) {
				while(i++ < c.defaultItemCount) {
					this.addItem();
				}
			}
			return this;
		},
		getData: function() {
			var ud;
			var cs = this.$ || {}
			var data = util.clone(this.vm.getItem('data'));
			util.each(data, function(item, index) {
				util.each(item.links, function(link) {
					// 未填写链接，则跳过此项
					if (!link.uri) {
						return null;
					}
					// 获取视频链接类型
					link.type = cs[link._typeModuleName] && cs[link._typeModuleName].getValue(true).id;
					link.time = parseFloat(link.time);
					link._typeModuleName = ud;
					link._loading = ud;
				});
			});
			return data;
		},
		setData: function(data) {
			var that = this;
			// 确保所有属性都存在
			util.each(data, function(item) {
				item = that.initItemFields({
					// id
					creativeId: item._id,
					// 类型
					type: item.Type,
					// 名称
					name: item.Name,
					// 宽度
					width: item.Width,
					// 高度
					height: item.Height,
					// 是否允许跳过
					allowSkip: item.AllowSkip,
					// 视频链接
					links: item.Links
				});
				util.each(item.links, function(link) {
					link.time = parseInt(link.time, 10) + LANG("秒");
					return that.initLinkItemFields(link);
				});
				return item;
			});
			this.vm.setItem('data', data);
		},
		validate: function(data) {
			var isPass = true;
			util.each(data || this.getData(), function(item) {
				var type_stack = {};
				var curTime;
				var isItemPass = true;

				// 检查是否未填写视频链接
				if (!item.links || !item.links.length) {
					isPass = false;
					pubjs.alert(LANG("创意【%1】未填写视频链接", item.name));
					return false;
				}

				if(!item.width || !item.height) {
					isPass = false;
					pubjs.alert(LANG("创意【%1】尺寸填写不完整", item.name));
					return false;
				}

				util.each(item.links, function(link) {
					// 检查时长是否一致
					if (curTime && link.time && curTime != curTime) {
						isItemPass = false;
						pubjs.alert(LANG("创意【%1】的视频链接时长不一致", item.name));
						return false;
					}
					curTime = link.time;

					// 检查是否类型为空
					if (!link.type) {
						isItemPass = false;
						pubjs.alert(LANG("还未设置视频链接【%1】的视频类型", item.name));
						return false;
					}

					// 检查是否视频链接重复
					if (link.type in type_stack) {
						isItemPass = false;
						pubjs.alert(LANG("创意【%1】的视频链接类型重复", item.name));
						return false;
					}
					type_stack[link.type] = 1;
				});

				if (!isItemPass) {
					isPass = false;
				}
			});

			return isPass;
		}
	});
	exports.videoOuterlink = VideoOuterlink;

	// 选项卡-手工添加物料
	var AddManually = view.container.extend({
		init: function(config){
			config = pubjs.conf(config, {
				'class': 'uk-form',
				'tplFile': '/tpl/sweety/tab/addManually.html',
				'view_model': {
					// 创意数据
					'data': [],
					// 删除创意按钮
					'closeItem': this.closeItem
				},
				'uploader': {
					'subModule': 'modules/upload.manually',
					'hasProgress': true,
					'hasTip': false,
					'filter': {
						mime_types: [ //只允许上传图片文件和rar压缩文件
							{title: "图片文件", extensions: "jpg,jpeg,gif,png"}
						]
					}
				}
			});

			// 保存上传图片的数据
			this.$uploader = {};
			this.Super('init', arguments);
		},
		afterBuild: function() {
			var config = {
				'add': {
					'width': 0,
					'value': LANG('添加创意'),
					'class': 'btn btn-default mt10'
				}
			}
			this.buildFromTemplate(config);
		},
		afterBuildTemplate: function() {
			// this.addItem();
		},
		setData: function(data){
			var self = this;
			this.vm.$.data = [];
			data.forEach(function(creative){
				var detail = {};
				detail.creativeId = creative._id;
				detail.name = creative.Name;
				detail.width = creative.Width;
				detail.height = creative.Height;
				detail.html_snippet = (creative.Adm.Html && creative.Adm.Html != '')? creative.Adm.Html : creative.Adm.SSL;
				detail.isSSL = (creative.Adm.SSL && creative.Adm.SSL != '') ? true : false
				// options(仅作显示使用)
				detail.thumb = creative.Thumb;
				detail.path = creative.Path;
				detail.type = creative.Material ? creative.Material.FileType : creative.Material;
				detail.size = creative.Material ? creative.Material.FileSize && ((Number(creative.Material.FileSize / 1024)).toFixed(1) + "KB") : creative.Material;
				detail.previewUrl = creative.Cover;

				self.addItem(detail);
			});
		},
		getData: function(){
			var data = this.vm.getItem('data');
			var result = [];
			util.each(data, function(value, index){
				result[index] = {
					'index'		: value.index,
					'creativeId': value.creativeId || 0,
					'Name'		: value.name,
					'Width'		: value.width,
					'Height'	: value.height,
					'Html_snippet': value.html_snippet,
					'isSSL'		: value.isSSL,
					'type'		: 'addManually'
					// 图片部分待最终上传的时候再获取数据，保证数据的准确性
				};

			});
			return result;
		},
		addItem: function(data) {
			var self = this;
			if (!data) {
				data = {};
			}
			if (this.vm.$.data.length == 0) {
				// 清空模块
				for (var key in this.$uploader) {
					self.$uploader[key] = null;
					delete self.$uploader[key];
					self.removeChild(key);
				}
			}
			var date = util.date('YmdHis');
			var index = 'uploader_' + date;
			while (this.$uploader[index]) {
				index += 'v';
			}
			this.vm.$.data.push ({
				'index': index,
				'creativeId': data.creativeId || 0,
				'width': data.width || '',
				'height': data.height || '',
				'name': data.name || LANG('新建创意包')+'_'+ date + '_' + LANG('手工物料'),
				'isSSL': data.isSSL || false,
				'html_snippet': data.html_snippet || '' // 动态代码
			});

			// 创建上传模块
			var target = self.$el.find('#' + index);
			var uploadParam = {
				'target': target
			};
			var uploadCreative = pubjs.config('uploader/creative');
			var upload = self.getConfig('uploader');
			if(uploadParam.target)
			{
				self.createAsync(index, 'modules/upload.base',
					$.extend({}, uploadCreative, upload, uploadParam)
					, function(mod) {
						if (mod && data.path && data.path != '') {
							mod.setValue(data);
						}
					}
				);
				// 保存模块
				self.$uploader[index] = self.$[index];
			}
		},
		closeItem: function(index) {
			var name = this.vm.$.data[index].index;
			// 删除数据
			this.vm.$.data.splice(index,1);
			// 删除子模块
			this.removeChild(name);
			// 删除上传数据
			this.$uploader[name] = null;
			delete this.$uploader[name];
		},
		onInputClick: function(ev){
			if(ev.name == 'add'){
				this.addItem();
			}
			return false;
		},
		validate: function(data){
			var error;
			util.each( data, function(da){
				if(da && da.Name != '' && da.Width != '' && da.Height != '' && da.Html_snippet != ''){
					if(!util.isNumber(da.Width) || !util.isNumber(da.Height)){
						error = LANG('尺寸必须为数字.');
					}
				}
				else {
					error = LANG('请填上对应的选项,名称,代码,尺寸等');
				}
				if(error){
					return false;
				}
			});

			if(error){
				pubjs.alert(error);
				return false;
			}
			return true;
		},
		checkUploadInfo: function(data) {
			for (var i = 0; i < data.length; i++) {
				var uploader = this.$uploader[data[i].index].getValue()[0];
				if (uploader) {
					data[i].FileId = uploader.fileId;
				} else {
					data[i].FileId = 'none';
				}
			}
			return data;
		},
		reset: function() {
			var self = this;
			while (self.vm.$.data.length) {
				self.closeItem(0);
			}
			return self;
		}
	});
	exports.addManually = AddManually;

});